<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="条件名称" prop="conditionName">
        <el-input v-model="formData.conditionName" placeholder="请输入条件名称" />
      </el-form-item>
      <el-form-item label="职业代码" prop="professionCode">
        <el-select
          v-model="formData.professionCode"
          placeholder="请选择职业代码"
          filterable
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="profession in professionList"
            :key="profession.professionCode"
            :label="`${profession.professionCode}（${profession.professionName}）`"
            :value="profession.professionCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="技能等级" prop="skillLevel">
        <el-select v-model="formData.skillLevel" placeholder="请选择技能等级">
          <el-option label="五级" value="五级" />
          <el-option label="四级" value="四级" />
          <el-option label="三级" value="三级" />
          <el-option label="二级" value="二级" />
          <el-option label="一级" value="一级" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价方式" prop="evaluationMethod">
        <el-select v-model="formData.evaluationMethod" placeholder="请选择评价方式">
          <el-option label="认定评价" value="assessment" />
          <el-option label="考试评价" value="examination" />
          <el-option label="混合评价" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="条件类型" prop="conditionType">
        <el-select v-model="formData.conditionType" placeholder="请选择条件类型">
          <el-option label="学历要求" value="education" />
          <el-option label="工作年限" value="work_experience" />
          <el-option label="培训经历" value="training" />
          <el-option label="证书要求" value="certificate" />
          <el-option label="其他要求" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="条件参数" prop="conditionParameters">
        <el-input
          v-model="formData.conditionParameters"
          type="textarea"
          :rows="3"
          placeholder="请输入条件参数（JSON格式）"
        />
      </el-form-item>
      <el-form-item label="验证规则" prop="validationRules">
        <el-input
          v-model="formData.validationRules"
          type="textarea"
          :rows="3"
          placeholder="请输入验证规则"
        />
      </el-form-item>
      <el-form-item label="是否必需" prop="isRequired">
        <el-radio-group v-model="formData.isRequired">
          <el-radio :value="true">必需</el-radio>
          <el-radio :value="false">可选</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="逻辑操作符" prop="logicOperator">
        <el-select v-model="formData.logicOperator" placeholder="请选择逻辑操作符">
          <el-option label="AND" value="AND" />
          <el-option label="OR" value="OR" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="conditionOrder">
        <el-input-number v-model="formData.conditionOrder" :min="1" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="状态" prop="conditionStatus">
        <el-radio-group v-model="formData.conditionStatus">
          <el-radio :value="0">禁用</el-radio>
          <el-radio :value="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, unref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getApplicationCondition,
  createApplicationCondition,
  updateApplicationCondition
} from '@/api/eval/condition'
import { getSimpleProfessionList } from '@/api/eval/profession'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const dialogTitle = computed(() => (formData.value.id ? '修改申报条件' : '添加申报条件'))
const formLoading = ref(false)
const formRef = ref()
const professionList = ref<any[]>([])
const formData = ref({
  id: undefined,
  conditionName: '',
  professionCode: '',
  skillLevel: '',
  evaluationMethod: '',
  conditionType: '',
  conditionParameters: '',
  validationRules: '',
  isRequired: true,
  logicOperator: '',
  conditionOrder: 1,
  conditionStatus: 1
})
const formRules = ref({
  conditionName: [{ required: true, message: '条件名称不能为空', trigger: 'blur' }],
  professionCode: [{ required: true, message: '职业代码不能为空', trigger: 'blur' }],
  skillLevel: [{ required: true, message: '技能等级不能为空', trigger: 'change' }],
  evaluationMethod: [{ required: true, message: '评价方式不能为空', trigger: 'change' }],
  conditionType: [{ required: true, message: '条件类型不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number, copyData?: any) => {
  dialogVisible.value = true
  resetForm()

  // 如果有复制数据，直接使用复制数据
  if (copyData) {
    Object.assign(formData.value, copyData)
    return
  }

  // 如果有ID，从后端获取数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getApplicationCondition(id)
      Object.assign(formData.value, data)
    } catch (error) {
      console.error('获取申报条件详情失败:', error)
      ElMessage.error('获取申报条件详情失败')
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  const elForm = unref(formRef)
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (data.id) {
      await updateApplicationCondition(data)
      ElMessage.success('修改成功')
    } else {
      await createApplicationCondition(data)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存申报条件失败:', error)
    ElMessage.error('保存失败')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    conditionName: '',
    professionCode: '',
    skillLevel: '',
    evaluationMethod: '',
    conditionType: '',
    conditionParameters: '',
    validationRules: '',
    isRequired: true,
    logicOperator: '',
    conditionOrder: 1,
    conditionStatus: 1
  }
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

/** 获取职业列表 */
const loadProfessionList = async () => {
  try {
    const data = await getSimpleProfessionList()
    professionList.value = data || []
  } catch (error) {
    console.error('获取职业列表失败:', error)
    ElMessage.error('获取职业列表失败')
  }
}

/** 组件挂载时加载职业列表 */
onMounted(() => {
  loadProfessionList()
})

defineExpose({ open })
</script> 